<template>
  <div class="user-management-page">
    <!-- 查询表单 -->
    <UserSearchForm
      :loading="loading"
      @search="handleSearch"
      @reset="handleReset"
      @update:search-params="handleSearchParamsChange"
    />
    
    <!-- 用户列表 -->
    <UserList
      :table-data="tableData"
      :pagination="pagination"
      :loading="loading"
      :selection="selection"
      @update:selection="handleSelectionChange"
      @page-change="handlePageChange"
      @sort="handleSort"
      @refresh="handleRefresh"
      @export="handleExport"
      @add="handleAdd"
      @action="handleAction"
    />
    
    <!-- 新增用户弹窗 -->
    <UserAddDialog
      v-model:visible="addDialogVisible"
      :loading="dialogLoading"
      @submit="handleAddSubmit"
      @close="handleAddClose"
    />
    
    <!-- 编辑用户弹窗 -->
    <UserEditDialog
      v-model:visible="editDialogVisible"
      :user-data="editingUser"
      :loading="dialogLoading"
      @submit="handleEditSubmit"
      @close="handleEditClose"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useConfirmDialog } from '@/composables/useConfirmDialog'
import UserSearchForm from './modules/UserSearchForm.vue'
import UserList from './modules/UserList.vue'
import UserAddDialog from './modules/UserAddDialog.vue'
import UserEditDialog from './modules/UserEditDialog.vue'
import type { Pagination, TableAction } from '@/types'

const router = useRouter()
const { deleteConfirm } = useConfirmDialog()

// 响应式数据
const loading = ref(false)
const dialogLoading = ref(false)
const selection = ref<any[]>([])
const searchParams = ref({})

// 弹窗状态
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const editingUser = ref<any>(null)

const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const tableData = ref([
  {
    id: 1,
    username: 'admin',
    nickname: '管理员',
    email: 'admin@example.com',
    phone: '13800138000',
    avatar: 'https://via.placeholder.com/40',
    status: 1,
    roles: ['管理员', '超级管理员'],
    createTime: '2024-01-01 10:00:00',
    lastLoginTime: '2024-01-15 14:30:00'
  },
  {
    id: 2,
    username: 'user001',
    nickname: '张三',
    email: 'zhangsan@example.com',
    phone: '13800138001',
    avatar: '',
    status: 1,
    roles: ['普通用户'],
    createTime: '2024-01-02 09:15:00',
    lastLoginTime: '2024-01-14 16:20:00'
  },
  {
    id: 3,
    username: 'user002',
    nickname: '李四',
    email: 'lisi@example.com',
    phone: '13800138002',
    avatar: 'https://via.placeholder.com/40',
    status: 0,
    roles: ['普通用户', '测试用户'],
    createTime: '2024-01-03 11:30:00',
    lastLoginTime: null
  },
  {
    id: 4,
    username: 'user003',
    nickname: '王五',
    email: 'wangwu@example.com',
    phone: '13800138003',
    avatar: '',
    status: 1,
    roles: ['普通用户'],
    createTime: '2024-01-04 14:45:00',
    lastLoginTime: '2024-01-13 10:15:00'
  },
  {
    id: 5,
    username: 'user004',
    nickname: '赵六',
    email: 'zhaoliu@example.com',
    phone: '13800138004',
    avatar: 'https://via.placeholder.com/40',
    status: 1,
    roles: ['普通用户'],
    createTime: '2024-01-05 16:20:00',
    lastLoginTime: '2024-01-12 09:30:00'
  }
])

// 初始化数据
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新分页信息
    pagination.total = 25 // 模拟总数
    
    console.log('加载用户数据:', {
      searchParams: searchParams.value,
      pagination: pagination
    })
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理搜索参数变化
const handleSearchParamsChange = (params: Record<string, any>) => {
  searchParams.value = params
}

// 处理搜索
const handleSearch = (params: Record<string, any>) => {
  console.log('搜索参数:', params)
  searchParams.value = params
  pagination.currentPage = 1
  loadData()
}

// 处理重置
const handleReset = () => {
  console.log('重置搜索')
  searchParams.value = {}
  pagination.currentPage = 1
  loadData()
}

// 处理选择变化
const handleSelectionChange = (newSelection: any[]) => {
  console.log('选择变化:', newSelection)
  selection.value = newSelection
}

// 处理分页变化
const handlePageChange = (page: number, pageSize: number) => {
  console.log('分页变化:', page, pageSize)
  pagination.currentPage = page
  pagination.pageSize = pageSize
  loadData()
}

// 处理排序
const handleSort = (sortField: string, sortOrder: number) => {
  console.log('排序变化:', sortField, sortOrder)
  loadData()
}

// 处理刷新
const handleRefresh = () => {
  console.log('刷新数据')
  loadData()
}

// 处理导出
const handleExport = () => {
  console.log('导出数据')
  // 实现导出逻辑
}

// 处理新增
const handleAdd = () => {
  console.log('新增用户')
  addDialogVisible.value = true
}

// 处理操作
const handleAction = async (action: TableAction, row: any, index: number) => {
  console.log('执行操作:', action.key, row, index)
  
  switch (action.key) {
    case 'edit':
      editingUser.value = row
      editDialogVisible.value = true
      break
    case 'view':
      router.push(`/system/user/detail/${row.id}`)
      break
    case 'delete':
      const confirmed = await deleteConfirm(`用户 "${row.nickname}"`)
      if (confirmed) {
        deleteUser(row.id)
      }
      break
  }
}

// 处理新增提交
const handleAddSubmit = async (data: any) => {
  dialogLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 添加到表格数据
    const newUser = {
      id: Date.now(),
      ...data,
      roles: data.roles ? data.roles.split(',') : [],
      avatar: '',
      createTime: new Date().toLocaleString('zh-CN'),
      lastLoginTime: null
    }
    
    tableData.value.unshift(newUser)
    pagination.total++
    
    addDialogVisible.value = false
    console.log('新增用户成功:', newUser)
  } catch (error) {
    console.error('新增用户失败:', error)
  } finally {
    dialogLoading.value = false
  }
}

// 处理新增关闭
const handleAddClose = () => {
  addDialogVisible.value = false
}

// 处理编辑提交
const handleEditSubmit = async (data: any) => {
  dialogLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新表格数据
    const index = tableData.value.findIndex(item => item.id === data.id)
    if (index > -1) {
      tableData.value[index] = {
        ...tableData.value[index],
        ...data,
        roles: data.roles ? data.roles.split(',') : []
      }
    }
    
    editDialogVisible.value = false
    editingUser.value = null
    console.log('编辑用户成功:', data)
  } catch (error) {
    console.error('编辑用户失败:', error)
  } finally {
    dialogLoading.value = false
  }
}

// 处理编辑关闭
const handleEditClose = () => {
  editDialogVisible.value = false
  editingUser.value = null
}

// 删除用户
const deleteUser = async (id: number) => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 从表格数据中移除
    const index = tableData.value.findIndex(item => item.id === id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      pagination.total--
    }
    
    console.log('删除用户成功:', id)
  } catch (error) {
    console.error('删除用户失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.user-management-page {
  padding: 0;
}

/* 强制缩小下拉框样式 */
.user-management-page :deep(.p-dropdown) {
  height: 32px !important;
  min-height: 32px !important;
  max-height: 32px !important;
  font-size: 12px !important;
}

.user-management-page :deep(.p-dropdown .p-dropdown-label) {
  height: 32px !important;
  padding: 6px 12px !important;
  font-size: 12px !important;
  line-height: 20px !important;
  display: flex !important;
  align-items: center !important;
}

.user-management-page :deep(.p-dropdown .p-dropdown-trigger) {
  height: 32px !important;
  width: 32px !important;
}

.user-management-page :deep(.p-dropdown .p-dropdown-trigger .p-dropdown-trigger-icon) {
  font-size: 12px !important;
}

.user-management-page :deep(.p-dropdown .p-dropdown-label-container) {
  height: 32px !important;
  line-height: 20px !important;
}

/* 用户管理页面下拉框placeholder样式 */
.user-management-page :deep(.p-dropdown .p-dropdown-label.p-placeholder) {
  font-size: 12px !important;
  line-height: 20px !important;
  color: #6c757d !important;
}

.user-management-page :deep(.p-dropdown .p-dropdown-label) {
  font-size: 12px !important;
  line-height: 20px !important;
}

/* 用户管理页面下拉框选中值样式 */
.user-management-page :deep(.p-dropdown .p-dropdown-label:not(.p-placeholder)) {
  font-size: 12px !important;
  line-height: 20px !important;
  color: #333 !important;
}

/* 下拉框选项字体样式 */
.user-management-page :deep(.p-dropdown-panel .p-dropdown-items .p-dropdown-item) {
  font-size: 12px !important;
  line-height: 20px !important;
  padding: 6px 12px !important;
}

.user-management-page :deep(.p-multiselect-panel .p-multiselect-items .p-multiselect-item) {
  font-size: 12px !important;
  line-height: 20px !important;
  padding: 6px 12px !important;
}
</style>